package com.wanghua.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanghua.common.utils.PageUtils;
import com.wanghua.common.utils.Query;
import com.wanghua.mall.product.dao.AttrDao;
import com.wanghua.mall.product.entity.AttrEntity;
import com.wanghua.mall.product.entity.AttrGroupEntity;
import com.wanghua.mall.product.entity.CategoryEntity;
import com.wanghua.mall.product.entity.ProductAttrValueEntity;
import com.wanghua.mall.product.service.AttrGroupService;
import com.wanghua.mall.product.service.AttrService;
import com.wanghua.mall.product.service.CategoryService;
import com.wanghua.mall.product.service.ProductAttrValueService;
import com.wanghua.mall.product.vo.AttrResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrGroupService attrGroupService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询属性详细的信息
     */
    @Override
    public AttrResponseVo infoDetail(Long id) {
        AttrEntity attrEntity = baseMapper.selectById(id);
        return convertAttrEntityToAttrResponseVo(attrEntity);
    }

    /**
     * 根据分类id获取基本属性列表
     */
    @Override
    public PageUtils baseListByCategoryId(Map<String, Object> params, Long categoryId) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        //基本属性
        queryWrapper.eq("attr_type", 1);
        return listByCategoryId(params, categoryId, queryWrapper);
    }

    /**
     * 根据分类id获取销售属性列表
     */
    @Override
    public PageUtils saleListByCategoryId(Map<String, Object> params, Long categoryId) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        //销售属性
        queryWrapper.eq("attr_type", 0);
        return listByCategoryId(params, categoryId, queryWrapper);
    }

    //根据属性分组id获取属性分组的关联的所有属性
    @Override
    public List<AttrEntity> getAttrByAttrGroupId(Long attrGroupId) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_group_id", attrGroupId);
        queryWrapper.select("id", "name", "value_select");
        return baseMapper.selectList(queryWrapper);
    }

    //批量移除属性与属性分组的关联(将属性的属性分组id字段置为0)
    @Override
    public void deleteAttrAttrGroupRelation(Long[] attrIds) {
        for (Long attrId : attrIds) {
            AttrEntity attrEntity = new AttrEntity();
            attrEntity.setId(attrId);
            attrEntity.setAttrGroupId(0L);
            baseMapper.updateById(attrEntity);
        }
    }

    //根据分组id获取所有未关联分组的基本属性列表（带分页）
    @Override
    public PageUtils getNotGroupAttr(Map<String, Object> params, Long attrGroupId) {
        //TODO 根据分类
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            queryWrapper.like("name", key);
        }
        //基本属性
        queryWrapper.eq("attr_type", 1);
        //分组id不相等
        queryWrapper.eq("attr_group_id", 0);
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    //添加属性与分组的关联
    @Override
    public void addAttrAttrGroupRelation(Long[] attrIds, Long attrGroupId) {
        for (Long attrId : attrIds) {
            AttrEntity attrEntity = baseMapper.selectById(attrId);
            attrEntity.setAttrGroupId(attrGroupId);
            baseMapper.updateById(attrEntity);
        }
    }

    //查出spu的所有规格参数
    @Override
    public List<ProductAttrValueEntity> getBySpu(Long spuId) {
        return productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
    }

    //更新spu的规格参数
    @Transactional
    @Override
    public void updateAttrBySpu(Long spuId, List<ProductAttrValueEntity> productAttrValueEntityList) {
        //删除spu之前对应的属性
        productAttrValueService.remove(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        //新增属性
        productAttrValueService.saveBatch(productAttrValueEntityList.stream().map((productAttrValueEntity) -> {
            productAttrValueEntity.setSpuId(spuId);
            return productAttrValueEntity;
        }).collect(Collectors.toList()));
    }


    //抽取根据分类id获取 基本/销售 属性列表的公告部分
    private PageUtils listByCategoryId(Map<String, Object> params, Long categoryId, QueryWrapper<AttrEntity> queryWrapper) {
        if (categoryId != 0) {
            queryWrapper.eq("category_id", categoryId);
        }
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            queryWrapper.like("name", key);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        List<AttrEntity> records = page.getRecords();
        //封装为AttrResponseVo对象
        List<AttrResponseVo> attrResponseVoList = records.stream().map(this::convertAttrEntityToAttrResponseVo).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrResponseVoList);
        return pageUtils;
    }


    //设置AttrEntity与AttrResponseVo多余的值
    private AttrResponseVo convertAttrEntityToAttrResponseVo(AttrEntity attrEntity) {
        //复制基本信息
        AttrResponseVo attrResponseVo = new AttrResponseVo();
        BeanUtils.copyProperties(attrEntity, attrResponseVo);
        //查询对应分组名称
        if (attrEntity.getAttrType() == 1) {
            Long attrGroupId = attrEntity.getAttrGroupId();
            if (attrGroupId != 0) {
                QueryWrapper<AttrGroupEntity> attrGroupEntityQueryWrapper = new QueryWrapper<>();
                attrGroupEntityQueryWrapper.eq("id", attrGroupId);
                attrGroupEntityQueryWrapper.select("name");
                attrResponseVo.setAttrGroupName(attrGroupService.getOne(attrGroupEntityQueryWrapper).getName());
            }
        }
        //查询分类名称
        Long categoryId = attrEntity.getCategoryId();
        if (categoryId != 0) {
            QueryWrapper<CategoryEntity> categoryEntityQueryWrapper = new QueryWrapper<>();
            categoryEntityQueryWrapper.eq("id", categoryId);
            categoryEntityQueryWrapper.select("name");
            attrResponseVo.setCategoryName(categoryService.getOne(categoryEntityQueryWrapper).getName());
            //查询分类完整路径
            attrResponseVo.setCategoryPath(categoryService.findCategoryPath(attrEntity.getCategoryId()));
        }

        return attrResponseVo;
    }

}